import socket
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad

# 预共享的加密密钥（必须与客户端相同）
KEY = b'ThisIsASecretKey'  # 16字节密钥

def decrypt_message(encrypted_data):
    """解密接收到的数据"""
    if len(encrypted_data) < 16:
        raise ValueError("接收到的数据长度不足，无法提取 IV")
    iv = encrypted_data[:16]  # 提取前16字节作为IV
    ciphertext = encrypted_data[16:]
    cipher = AES.new(KEY, AES.MODE_CBC, iv)
    return unpad(cipher.decrypt(ciphertext), AES.block_size)

# 创建TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 8888)
server_socket.bind(server_address)
server_socket.listen(1)
print(f"服务器正在监听 {server_address[0]}:{server_address[1]}")

client_socket, client_address = server_socket.accept()
print(f"接收到来自 {client_address} 的连接")

# 接收加密数据
encrypted_data = b''
while True:
    chunk = client_socket.recv(4096)
    if not chunk:
        break
    encrypted_data += chunk

# 解密并保存文件
try:
    decrypted_data = decrypt_message(encrypted_data)
    with open('received_file', 'wb') as f:
        f.write(decrypted_data)
    print("文件接收并解密成功")
except ValueError as ve:
    print(f"解密失败: {str(ve)}")
except Exception as e:
    print(f"解密失败: {str(e)}")

client_socket.close()
server_socket.close()